package com.zone.vehicle.superapp.view.home.home.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.appstore.entity.AppListItemEntity;
import com.zone.vehicle.lib.view.horizontalview.HorizontalView;
import com.zone.vehicle.lib.view.horizontalview.InfiniteScrollAdapter;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.databinding.FragmentAppHorizontalBinding;
import com.zone.vehicle.superapp.model.HomeViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import com.zone.vehicle.superapp.view.common.enums.ActionEnum;
import com.zone.vehicle.superapp.view.common.listener.ActionListener;
import com.zone.vehicle.superapp.view.home.home.main.adapter.HomeAppAdapterAdapter;

import org.apache.commons.lang3.ObjectUtils;

import java.util.List;

import static com.zone.vehicle.superapp.view.home.HomeFragment.APP_DETAIL_FRAGMENT;

public class AppHorizontalFragment extends BaseFragment {

    private static final String TAG = AppHorizontalFragment.class.getSimpleName();

    private FragmentAppHorizontalBinding binding;

    private InfiniteScrollAdapter<RecyclerView.ViewHolder> infiniteAdapter;

    private HomeViewModel viewModel;

    private HomeAppAdapterAdapter homeAppAdapterAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentAppHorizontalBinding.inflate(inflater);
        init();
        return binding.getRoot();
    }

    private void init(){
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(HomeViewModel.class);
        homeAppAdapterAdapter = new HomeAppAdapterAdapter(null, new AppItemOnClickListener(), getActivity());
        binding.itemPicker.setAdapter(homeAppAdapterAdapter);
        binding.itemPicker.addScrollListener(new HorizontalView.ScrollListener<RecyclerView.ViewHolder>() {
            @Override
            public void onScroll(float scrollPosition, int currentPosition, int newPosition, @Nullable RecyclerView.ViewHolder currentHolder, @Nullable RecyclerView.ViewHolder newCurrent) {
//                Log.d(TAG, "scrollPosition="+scrollPosition+" currentPosition="+currentPosition+" newPosition="+newPosition);
                if (ObjectUtils.isNotEmpty(viewModel.getHomeAppList())){
                    List<AppListItemEntity> appEntityList = (List<AppListItemEntity>) viewModel.getHomeAppList().getValue();
                    if (currentPosition >= appEntityList.size()/4){
                        moreData();
                    }
                }
            }
        });
        addListener(new ActionListener() {
            @Override
            public boolean onAction(ActionEnum action) {
                return false;
            }

            @Override
            public boolean onPageChanged(String pageName) {
                if (pageName.equals("AppHorizontalFragment")){
                    refreshData();
                    return true;
                }
                return false;
            }
        });
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result)){
                    if (result.getResultCode().equals("1")){
                        showErrorPage(1);
                    }else {
                        showErrorPage(3);
                    }
                }
            }
        });
        viewModel.getHomeAppList().observe(getViewLifecycleOwner(), new Observer<List<AppListItemEntity>>() {
            @Override
            public void onChanged(List<AppListItemEntity> appEntities) {
                homeAppAdapterAdapter.setData(appEntities);
                homeAppAdapterAdapter.notifyDataSetChanged();
                binding.itemPicker.scrollToPosition(1);
                if (ObjectUtils.isEmpty(appEntities)){
//                    showErrorPage(1);
                }else {
                    showErrorPage(0);
                }
            }
        });
        homeAppAdapterAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void refreshData() {
        viewModel.clearHome();
        moreData();
    }

    private void moreData() {
        viewModel.getHomeAppListData(requireContext());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    public class AppItemOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            AppListItemEntity app = (AppListItemEntity)v.getTag();
            Log.d(TAG, "app:"+app.getProductName());
            AppDetailEntity entity = app.buildAppDetailEntity();
            viewModel.setCurrentAppEntity(entity);
            changePage(APP_DETAIL_FRAGMENT);
        }
    }

    @Override
    public void showErrorPage(int type){
        switch (type){
            case 1://no data
                binding.itemPicker.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_no_data);
                binding.bottom.setVisibility(View.GONE);
                break;
            case 2://no wifi
                binding.itemPicker.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_no_wifi);
                binding.bottom.setVisibility(View.VISIBLE);
                break;
            case 3://error server
                binding.itemPicker.setVisibility(View.GONE);
                binding.errorLayout.setVisibility(View.VISIBLE);
                binding.top.setVisibility(View.VISIBLE);
                binding.top.setText(R.string.error_server);
                binding.bottom.setVisibility(View.VISIBLE);
                break;
            default:
                binding.itemPicker.setVisibility(View.VISIBLE);
                binding.errorLayout.setVisibility(View.GONE);
                binding.top.setVisibility(View.GONE);
                binding.bottom.setVisibility(View.GONE);
        }
        binding.bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshData();
            }
        });
    }
}
